package com.zytlifeservice.service;

import com.zytlifeservice.domain.User;
import com.zytlifeservice.domain.find.Integral;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.UserRepository;
import com.zytlifeservice.repository.VerifyRepository;
import com.zytlifeservice.util.TextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by MJS on 2017/4/22.
 */

@Service
public class UserService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private VerifyRepository verifyRepository;

    @Autowired
    private VerifyService verifyService;

    public User add(User user, String verify) {
        //要防止重复注册。以手机号为标识检验。返回已经注册，请登陆。
        User byMobile = userRepository.findByMobile(user.getMobile());
        if (byMobile != null) {
            throw new UserException("用户已经注册，请登录", 103);
        }
        verifyService.checkVerifyForRegister(user.getMobile(), verify);
        user.setCreateTime(new Date());
        User save = userRepository.save(user);
        if (save == null) {
            throw new UserException("添加失败", 105);
        }
        save.setStoreId("store" + save.getUserId());
        userRepository.save(save);
        save.setPassword("");
        return save;
    }

    /*登陆*/
    public User login(String mobile, String password) {
        if (TextUtil.isEmpty(mobile) || TextUtil.isEmpty(password)) {
            throw new UserException("用户名和密码不能为空", 101);
        }
        if (userRepository.findByMobile(mobile) == null) {
            throw new UserException("用户不存在", 103);
        }
        User user = userRepository.findByMobileAndPassword(mobile, password);
        if (user == null) {
            throw new UserException("用户名或密码错误", 102);
        }
        user.setPassword("");
        return user;
    }

    /*忘记密码*/
    public void forgetPassword(String mobile, String verify, String password) {
        User user = userRepository.findByMobile(mobile);
        if (user == null) {
            throw new UserException("用户不存在", 104);
        }

        if (TextUtil.isEmpty(password)) {
            throw new UserException("密码不能为空", 104);
        }
        verifyService.checkVerifyForRegister(mobile, verify);
        user.setPassword(password);
        if (userRepository.save(user) == null) {
            throw new UserException("修改密码失败", 104);
        }
    }


    /*
        修改密码 ,不用判断，修改的始终是该手机号对应的账户。
     */
    public void updatePassword(String mobile, String oldPassword, String newPassword, String verify) {
        User user = userRepository.findByMobile(mobile);
        if (user == null) {
            throw new UserException("用户不存在", 103);
        }
        if (TextUtil.isEmpty(oldPassword) || TextUtil.isEmpty(newPassword)) {
            throw new UserException("密码不能为空", 104);
        }

        verifyService.checkVerifyForRegister(user.getMobile(), verify);

        if (!oldPassword.equals(user.getPassword())) {
            throw new UserException("原密码出错", 105);
        }
        user.setPassword(newPassword);
        User res = userRepository.save(user);
        if (res == null) {
            throw new UserException("密码修改失败", 104);
        }
    }


    /*修改用户信息*/
    public User update(User user, String verify) {
        LOGGER.info("update verify={}", verify);
        LOGGER.info("update user={}", user);
        User save = userRepository.findOne(user.getUserId());
        if (save == null) {
            throw new UserException("用户不存在", 102);
        }

        verifyService.checkVerifyForRegister(save.getMobile(), verify);
//        真实姓名
//         性别
//        身份证
//        电话号码
//        详细地址
//        银行
//        银行卡号
        if (TextUtil.isEmpty(user.getName())) {
            throw new UserException("姓名不能为空", 102);
        } else {
            save.setName(user.getName());
        }

        if (user.getSex() == 0 || user.getSex() == 1) {
            save.setSex(user.getSex());
        } else {
            throw new UserException("性别只能为男或女", 102);
        }

        //TODO 后期加上对于基本格式验证
        if (TextUtil.isEmpty(user.getIdentityNum())) {
            throw new UserException("身份证不能为空", 102);
        } else {
            save.setIdentityNum(user.getIdentityNum());
        }

        if (TextUtil.isEmpty(user.getAddress())) {
            throw new UserException("详细地址不能为空", 102);
        } else {
            save.setAddress(user.getAddress());
        }

        if (TextUtil.isEmpty(user.getBank())) {
            throw new UserException("银行不能为空", 102);
        } else {
            save.setBank(user.getBank());
        }

        if (TextUtil.isEmpty(user.getBankCardNum())) {
            throw new UserException("银行卡号不能为空", 102);
        } else {
            save.setBankCardNum(user.getBankCardNum());
        }
        User result = userRepository.save(save);
        if (result == null) {
            throw new UserException("修改失败", 105);
        }
        result.setPassword("");
        return result;
    }


    /*
    修改用户头像
     */
    public void updateHeadImg(long userId, String headImg) {
        User user = userRepository.findOne(userId);
        if (user == null) {
            throw new UserException("用户不存在", 103);
        }
        if (TextUtil.isEmpty(headImg)) {
            throw new UserException("头像路径不能为空", 103);
        }
        user.setHeadIcon(headImg);
        if (userRepository.save(user) == null) {
            throw new UserException("修改失败", 103);
        }
    }

    /*
    根据id查询用户
     */
    public User queryUserInfo(long userId) {
        User user = userRepository.findOne(userId);
        if (user == null) {
            throw new UserException("用户不存在", 103);
        }
        user.setPassword("");
        return user;
    }

    //查询单个用户
    public User findOddUser(Long id) {
        return userRepository.findOne(id);
    }

    /**
     * @param userId     用户ID
     * @param integral   积分
     * @param optionType 积分操作:0.增积分1.减积分
     * @return
     */
    @Transactional
    public Integer updateToIntegral(Long userId, Integer integral, Integer optionType) {
        //获取当前积分
        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 202);
        }

        Integer userIntegral = one.getUserIntegral();
        int oldIntegral = 0;
        if (userIntegral != null) {
            oldIntegral = one.getUserIntegral();
        }

        Integer result = 0;
        if (optionType == Integral.TYPE_ADD) {//增
            Integer newIntegral = integral + oldIntegral;
            try {
                result = 1;
                userRepository.updateIntegral(newIntegral, userId);
            } catch (Exception ex) {
                result = 0;
                ex.printStackTrace();
            }
        } else if (optionType == Integral.TYPE_MINUS) {//减
            if (oldIntegral >= integral) {//个人积分大于等于兑换积分才可以正常兑换
                Integer newIntegral = oldIntegral - integral;
                try {
                    userRepository.updateIntegral(newIntegral, userId);
                    result = 1;
                } catch (Exception ex) {
                    result = 0;
                    ex.printStackTrace();
                }
            } else {
                result = -1;
            }
        }
        return result;
    }
}
